/**
 *@auther: tang
 *@Date: 2021-02-01
 *Project: p2pPlatformSys
 *Lang: TypeScript
 */
import { Context } from 'egg';

export default function authorizationMiddleware(): any {
  return async (ctx: Context, next: () => Promise<any>) => {
    if (ctx.get('Authorization')) {
      // console.log(ctx.get('Authorization'))
      const token = ctx.get('Authorization');
      try {
        ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      } catch (error) {
        if (error.name === 'TokenExpiredError') {
          /** 401 http错误 未经授权,访问由于凭证无效而被拒绝 */
          ctx.status = 405;
          ctx.body = {
            msg: 'token过期',
          };
          return;
        }
        ctx.status = 405;
        ctx.body = {
          msg: 'token失效',
        };
        return;

      }
      await next();
    } else {
      ctx.status = 405;
      ctx.body = {
        msg: '未发现token，无法访问',
      };
      return;
    }
  };
}
